package life.system.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.awt.image.BufferedImage;
import java.util.Hashtable;

public class QRCodeGenerator {
    private final static String CHARSET ="utf-8";

    private final static int QRSIZEE =300;

    // 二维码颜色
    private static final int BLACK =0xFF000000;
    // 二维码颜色
    private static final int WHITE =0xFFFFFFFF;

    public static BufferedImage createImage(String id){
        String content = id;
        Hashtable<EncodeHintType, Object> hints =new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN,1);
        BitMatrix bitMatrix =null;
        try {
            bitMatrix =new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRSIZEE, QRSIZEE,hints);
        }catch (Exception e){
            e.printStackTrace();
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image =new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x =0; x < width; x++) {
            for (int y =0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

}
